import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, DatePicker, Form, Input, Row, Select, Spin, message } from 'antd';
import { Ref, useContext, useEffect, useRef } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { getCompanyName, getKeyRouter, getLoadMapList, getPosName, getTenantID, getUserDepName, getUserName, onCloseModalCommon } from '@/utils';
import { TagSelectNew } from '@/components/TagSelectNew';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import moment from 'moment';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import { addMemoirService, editMemoirService, getMemoirByIdService } from '../services';

const { TextArea } = Input;
const DayDatePicket: any = DatePicker;

export const MemoirUpdateModal: React.FC<SupplierManageAPI.IMemoirUpdateModal> = ({ onClose, memoirCheckRows, reloadMemoirManage }) => {
  /** 弹框Ref */
  const memoirModalRef: Ref<IOneModalRef> = useRef(null);

  /** 表单 */
  const [memoirUpdateForm] = Form.useForm();

  /** 获取上下文 */
  const { locationID, memoirDataList, supplierDispath } = useContext(SupplierLocaldataContext);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.MEMOIR_TYPE}`, //大事件类型
  ]);

  /**
   * 详情接口回调
   * @param res
   */
  const getMemoirByIdCallback = (res: any) => {
    if (res && res?.msgFlag) {
      memoirUpdateForm?.setFieldsValue({
        ...res?.obj,
        memoirTime: res?.obj?.memoirTime ? moment(res?.obj?.memoirTime) : null,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情接口 */
  const { getMemoirByIdInfo, getMemoirByIdLoading, getMemoirByIdRun } = getMemoirByIdService(getMemoirByIdCallback);

  /**
   * 详情接口回调
   * @param res
   */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res.msg);
      reloadMemoirManage();
      onCloseModalCommon(memoirModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入添加接口 */
  const { addMemoirLoading, addMemoirRun } = addMemoirService(updateCallback);

  /** 引入编辑接口 */
  const { editMemoirLoading, editMemoirRun } = editMemoirService(updateCallback);

  /** 初始化 */
  useEffect(() => {
    console.log('memoirCheckRows=======================memoirCheckRows', memoirCheckRows);
    if (memoirCheckRows && memoirCheckRows?.key) {
      memoirUpdateForm?.setFieldsValue({
        ...memoirCheckRows,
        memoirTime: memoirCheckRows?.memoirTime ? moment(memoirCheckRows?.memoirTime) : null,
      });
    } else if (memoirCheckRows && memoirCheckRows?.id) {
      // getMemoirByIdRun({ id: memoirCheckRows?.id });
      memoirUpdateForm?.setFieldsValue({
        //模拟数据-王志龙
        ...memoirCheckRows,
        memoirTime: memoirCheckRows?.memoirTime ? moment(memoirCheckRows?.memoirTime) : null,
      });
    }
  }, [memoirCheckRows]);

  /** 保存负面影响 */
  const onSaveMemoir = () => {
    memoirUpdateForm?.validateFields()?.then((values: any) => {
      // 事迹类型
      const memoirTypeObj: Record<string, any> = loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MEMOIR_TYPE}`]?.find(
        (item: any) => item?.id == values?.memoirType,
      );
      let payload: Record<string, any> = {
        ...values,
        memoirTime: values?.memoirTime ? moment(values?.memoirTime).format('YYYY-MM-DD HH:mm:ss') : null,
        memoirTypeName: `${memoirTypeObj?.name}||${memoirTypeObj?.fontColor}`,
      };
      if (locationID) {
        /** 编辑供应商逻辑 */
        // if (getMemoirByIdInfo && getMemoirByIdInfo?.id) {
        //   const editPayload: Record<string, any> = {
        //     ...payload,
        //     id: getMemoirByIdInfo?.id,
        //     versionNum: getMemoirByIdInfo?.versionNum,
        //     supplierID: locationID,
        //   };
        //   editMemoirRun(editPayload);
        // } else {
        //   payload['supplierID'] = locationID;
        //   addMemoirRun(payload);
        // }

        /** 编辑接口 */
        const editPayload: Record<string, any> = {
          ...payload,
          id: memoirCheckRows?.id,
          versionNum: memoirCheckRows?.versionNum,
          supplierID: locationID,
        };
        editMemoirRun(editPayload);
      } else {
        /** 添加供应商逻辑 */
        let newMemoirList: Record<string, any>[] = [...memoirDataList];
        if (memoirCheckRows && memoirCheckRows?.key) {
          /** 编辑负面影响逻辑 */
          newMemoirList = newMemoirList?.filter((item: any) => item?.key != memoirCheckRows?.key);
          const editMemoirInfo: Record<string, any> = {
            ...memoirCheckRows,
            ...payload,
          };
          newMemoirList?.push(editMemoirInfo);
        } else {
          const addMemoirInfo: Record<string, any> = {
            ...payload,
            key: `memoirObj-${getKeyRouter()}`,
            createrName: getUserName(),
            createPositionName: getPosName(),
            createDepartmentName: getUserDepName(),
            createCompanyName: getCompanyName(),
            createTime: moment()?.format('YYYY-MM-DD HH:mm:ss'),
          };
          newMemoirList?.push(addMemoirInfo);
        }

        supplierDispath({
          type: ISupplierActionEnum.MEMOIRDATA_LIST,
          payload: newMemoirList,
        });
        onCloseModalCommon(memoirModalRef);
      }
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={memoirModalRef}
        title={memoirCheckRows?.id ? '编辑负面影响' : '添加负面影响'}
        width={document.body.clientWidth * 0.45}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 10px',
        }}
        onOk={onSaveMemoir}
        confirmLoading={getMemoirByIdLoading || editMemoirLoading || addMemoirLoading}
      >
        <Spin spinning={getMemoirByIdLoading || editMemoirLoading || addMemoirLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form form={memoirUpdateForm}>
              <Row>
                <Col span={24}>
                  <TagSelectNew
                    colSpan={24}
                    formLabel="是否有效"
                    formName="isOpen"
                    defalultKeys={memoirCheckRows?.isOpen}
                    formRequired={true}
                    radioList={[
                      {
                        value: 1,
                        name: '是',
                      },
                      {
                        value: 0,
                        name: '否',
                      },
                    ]}
                  />
                </Col>
                <Col span={24}>
                  <Form.Item label="事件类型" name="memoirType" rules={[{ required: true, message: '请选择事件类型' }]}>
                    <Select placeholder="请选择事件类型" loading={mapLoading}>
                      {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MEMOIR_TYPE}`]?.map((item: any) => {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            {item?.name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                {/* <Col span={24}>
                  <Form.Item
                    label="事件性质"
                    name="memoirNature"
                    rules={[{ required: true, message: '请选择事件性质' }]}
                    initialValue={'2'}
                  >
                    <Select placeholder="请选择事件性质">
                      <Select.Option key={'0'} value={'0'}>
                        无影响
                      </Select.Option>
                      <Select.Option key={'2'} value={'2'}>
                        正面影响
                      </Select.Option>
                      <Select.Option key={'1'} value={'1'}>
                        负面影响
                      </Select.Option>
                    </Select>
                  </Form.Item>
                </Col> */}
                <Col span={24}>
                  <Form.Item label="事件时间" name="memoirTime" rules={[{ required: true, message: '请选择事件时间' }]}>
                    <DayDatePicket
                      allowClear={true}
                      placeholder="请选择事件时间"
                      style={{ width: '100%' }}
                      disabledDate={(current: any) => {
                        return current && current > moment();
                      }}
                    />
                  </Form.Item>
                </Col>
                <UploadFormCommon
                  form={memoirUpdateForm}
                  fileFormName={'memoirImage'}
                  spanCol={24}
                  inRowProportion={12}
                  name={'attachFile'}
                  label="事件图片"
                  required={false}
                  accept={'.jpg|.png|.jpeg'}
                  url={'/supplierInfoController/uploadFile'}
                  downloadUrl={'/supplierInfoController/downloadFile'}
                  fileFormDelName={'delLicenceUrl'}
                  delFunc={() => {}}
                  maxFile={5}
                  fieldBusiPath={'supplier/info'}
                  defaultFiles={memoirCheckRows && JSON.stringify(memoirCheckRows) != '{}' ? memoirCheckRows?.memoirImage : null}
                  // defaultFiles={null} //模拟数据-王志龙
                >
                  事件图片
                </UploadFormCommon>
                <Col span={24}>
                  <Form.Item
                    label="事件结果"
                    name="memoirResult"
                    rules={[
                      {
                        required: true,
                        message: '请输入事件结果',
                      },
                    ]}
                  >
                    <TextArea placeholder={`请输入事件结果`} showCount maxLength={2000} autoSize={{ minRows: 4, maxRows: 6 }} />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item label="事件描述" name="memoirInfo">
                    <TextArea placeholder={`请输入事件描述`} showCount maxLength={2000} autoSize={{ minRows: 4, maxRows: 6 }} />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
